/*
 *  Copyright (C) 2010 Glauco
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.balisunrise.swing.commons;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.swing.JButton;
import javax.swing.JPanel;
import org.balisunrise.application.Application;
import org.balisunrise.builder.CommonFactory;
import org.balisunrise.builder.FactoryException;
import org.balisunrise.common.VisualAction;
import org.balisunrise.common.VisualEntityType;
import org.balisunrise.common.abstracts.AbstractVisualEntity;
import org.balisunrise.common.defaults.VEAUtil;
import org.balisunrise.common.events.BeforeCancelEvent;
import org.balisunrise.common.events.BeforeConfirmEvent;
import org.balisunrise.common.events.VisualActionEvent;
import org.balisunrise.common.listeners.EntityActionsListener;
import org.balisunrise.swing.components.panel.ActionPanel;

/**
 *
 * @author Glauco
 */
public class EntityActions extends AbstractVisualEntity
        implements org.balisunrise.common.EntityActions
        <VisualAction<JButton>, JPanel>{


    public static final String PROP_CONFIRMATION_ACTION = "confirmationAction";
    public static final String PROP_CANCELLATION_ACTION = "cancellationAction";
    public static final String PROP_ACTIONS = "actions";
    public static final String PROP_VISUAL_REPRESENTATION = "visualRepresentation";

    private VisualAction<JButton> confirmationAction;
    private VisualAction<JButton> cancellationAction;
    private List<VisualAction<JButton>> actions;
    private List<EntityActionsListener> listeners;
    private ActionPanel visualRepresentation;

    public EntityActions() {
        actions = new ArrayList<VisualAction<JButton>>();
        listeners = new ArrayList<EntityActionsListener>();
    }

    @Override
    public VisualAction<JButton>[] getActions() {
        return actions.toArray(new VisualAction[actions.size()]);
    }

    public void setActions(List<VisualAction<JButton>> actions) {

        if(actions == null)
            return ;

        this.actions = actions;
    }

    public void setVisualRepresentation(ActionPanel visualRepresentation) {
        ActionPanel old = this.visualRepresentation;
        this.visualRepresentation = visualRepresentation;
        changeSupport.firePropertyChange(PROP_VISUAL_REPRESENTATION, old,
                visualRepresentation);
    }

    @Override
    public void setConfirmationAction(VisualAction<JButton> action) {
        VisualAction<JButton> old = this.confirmationAction;
        this.confirmationAction = action;
        visualRepresentation.setConfirmationButton(
                action.getVisualRepresentation());
        changeSupport.firePropertyChange(PROP_CONFIRMATION_ACTION, old,
                confirmationAction);
    }

    @Override
    public void setCancellationAction(VisualAction<JButton> action) {
        this.cancellationAction = action;
        visualRepresentation.setCancellationButton(
                action.getVisualRepresentation());
    }

    @Override
    public void confirm() {

        org.balisunrise.common.Messenger m = VEAUtil.getMessenger(this);
        String beforeConfirmId = getName() + "_BEFORE_CONFIRM";
        m.removeMessage(beforeConfirmId);

        if(confirmationAction != null){
            // BEFORE CONFIRM EVENT
            try{
                BeforeConfirmEvent evt = CommonFactory.getFactory()
                        .createBeforeConfirmEvent(confirmationAction, this);
                for (EntityActionsListener listener : listeners) {
                    listener.beforeConfirm(evt);
                }
                getOwner().actionPerformed(evt);
            }catch(FactoryException ex){
                Application.get().getLogger().log(Level.SEVERE,
                        "EntityAction não pode criar BeforeConfirmEvent", ex);
            }catch(NullPointerException ex){
                Application.get().getLogger().log(Level.SEVERE,
                        "EntityAction não pode disparar BeforeConfirmEvent",ex);
                throw ex;
            }catch(RuntimeException ex){
                VEAUtil.getMessenger(this).addMessage(
                        beforeConfirmId,ex.getMessage(),Messenger.ERROR);
            }

            // CONFIRM ACTION
            VisualActionEvent evt = null;
            try{
                evt = CommonFactory.getFactory()
                        .createVisualActionEvent(this,confirmationAction);
            }catch(FactoryException ex){
                Application.get().getLogger().log(Level.SEVERE,
                        "EntityAction não pode criar VisualActionEvent", ex);
            }
            confirmationAction.perform(evt);
            
            for (EntityActionsListener listener : listeners) {
                listener.visualActionPerformed(evt);
            }
            getOwner().actionPerformed(evt);
        }
    }

    @Override
    public void cancel() {

        org.balisunrise.common.Messenger m = VEAUtil.getMessenger(this);
        String beforeCancelId = getName() + "_BEFORE_CANCEL";
        m.removeMessage(beforeCancelId);

        if (cancellationAction != null){
            // BEFORE CANCEL EVENT
            try{
                BeforeCancelEvent evt = CommonFactory.getFactory()
                        .createBeforeCancelEvent(cancellationAction, this);
                for (EntityActionsListener listener : listeners) {
                    listener.beforeCancel(evt);
                }
                getOwner().actionPerformed(evt);
            }catch(FactoryException ex){
                Application.get().getLogger().log(Level.SEVERE,
                        "EntityAction não pode criar BeforeCancelEvent", ex);
            }catch(NullPointerException ex){
                Application.get().getLogger().log(Level.SEVERE,
                        "EntityAction não pode disparar BeforeCancelEvent", ex);
                throw ex;
            }catch(RuntimeException ex){
                VEAUtil.getMessenger(this).addMessage(
                        beforeCancelId,ex.getMessage(),Messenger.ERROR);
            }

            // CANCEL ACTION
            VisualActionEvent evt = null;
            try{
                evt = CommonFactory.getFactory()
                        .createVisualActionEvent(this,confirmationAction);
            }catch(FactoryException ex){
                Application.get().getLogger().log(Level.SEVERE,
                        "EntityAction não pode criar VisualActionEvent", ex);
            }
            cancellationAction.perform(evt);

            for (EntityActionsListener listener : listeners) {
                listener.visualActionPerformed(evt);
            }
            getOwner().actionPerformed(evt);
        }
    }

    @Override
    public void addAction(VisualAction<JButton> action) {

        if(action == null)
            return ;

        actions.add(action);

        visualRepresentation.addAction(
                action.getVisualRepresentation(),actions.size());
    }

    @Override
    public void addAction(VisualAction<JButton> action, int index) {

        if(action == null)
            return ;

        if(actions.size() < index)
            actions.add(action);

        if(index < 0)
            actions.add(0, action);

        actions.add(index, action);

        visualRepresentation.addAction(action.getVisualRepresentation()
                , index);
    }

    @Override
    public void performAction(int index) {

        if (index < 0 || index >= actions.size())
            return ;

        VisualAction action = actions.get(index);
        if (action != null){
            VisualActionEvent evt = null;
            try{
                evt = CommonFactory.getFactory()
                        .createVisualActionEvent(this,action);
            }catch(FactoryException ex){
                Application.get().getLogger().log(Level.SEVERE,
                        "EntityAction não pode criar VisualActionEvent", ex);
            }
            action.perform(evt);
            for (EntityActionsListener listener : listeners) {
                listener.visualActionPerformed(evt);
            }
            getOwner().actionPerformed(evt);
        }
    }

    @Override
    public JPanel getVisualRepresentation() {
        return visualRepresentation;
    }

    /**
     * Retorna o tipo do VisualEntity.<BR>
     * Sempre retornará ENTITY_ACTIONS.
     * @return VisualEntityType.ENTITY_ACTIONS
     */
    @Override
    public VisualEntityType getVisualEntityType() {
        return VisualEntityType.ENTITY_ACTIONS;
    }

    @Override
    public void addEntityActionsListener(EntityActionsListener el) {
        listeners.add(el);
    }

    @Override
    public boolean removeEntityActionsListener(EntityActionsListener el) {
        return listeners.remove(el);
    }

    @Override
    public EntityActionsListener[] getEntityActionsListeners() {
        return listeners.toArray(new EntityActionsListener[]{});
    }
}
